// proxySubShopDevice.js
const app = getApp()
const util = require("../../utils/util.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    search: {
      searchAddShow: true,
      BtnTxt: '添加设备',
      searchTip: '输入设备号搜索',
      searchValue: '',
    },
    id:'',
    list:[],
    pagenum:1,
    remarkDialog:false,
    dialogValue:'',
    updateType: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id:options.id
    })
    this.shopDevice('defalut');
  },
  // 添加设备
  addTap:function(){
    var that = this;
    wx.scanCode({
      scanType: 'qrCode',
      success: function (res) {
        var obj = {};
        let url = res.result;
        if (url.indexOf("?") != -1) {
          var str = url.split('?')[1];
          var Arr = str.split("&");
          Arr.forEach(function (item) {
            var value = item.split('=')[1];
            var key = item.split('=')[0];
            obj[key] = value;
          })
          that.setData({
            thisSN: obj['code'],
          })
          var data = { sn: obj['code'] }
          // 验证sn是否存在
          app.post('manage/verifyDevce',data).then((res) =>{

            if (res.entity == false ){
              that.setData({
                remarkDialog: true,
                updateType: 'room'
              })
              var submitdata = {
                sn: obj['code'],
                shopid: that.data.id,
                version: obj['version'] || obj['type'],
                remark: that.data.dialogValue
              };
              // 添加设备
              app.post('agent/submitDevice', submitdata).then((res) => {
                if (res.code == 200) {
                  that.setData({
                    list: [],
                    pagenum: 1,
                    remark: '',
                  })
                  that.shopDevice('defalut')
                } else {
                  wx.showToast({
                    title: res.message,
                  })
                }

              }).catch((errMsg) => {
                console.log(errMsg);//错误提示信息
                wx.showToast({
                  title: errMsg,
                })
              })
            }else{
              wx.showToast({
                title: '设备已存在',
              })
            }
          }).catch((errMsg) =>{
            console.log(errMsg);//错误提示信息
            wx.showToast({
              title: errMsg,
            })
          })
          

        }
      },
      fail: function (res) {
        wx.showToast({
          title: '扫码失败',
        })
      }
    })
  },
  searchChange: function (event) {
    var detail = 'search.searchValue'
    this.setData({
      [detail]: event.detail
    })
  },
  // 搜索
  onSearch: function () {
    this.shopDevice('search');
  },
  // 获取列表
  shopDevice: function (type){
    var that = this;
    if (type == 'search') {
      that.setData({ list: [] })
    }
    var data = { id: that.data.id,page: that.data.pagenum, input: that.data.search.searchValue };
    app.post("agent/shopDevice", data).then((res) => {
      if (res.code == 200) {

        var list = that.data.list;
        var dataArr = res.list;
        list = list.concat(dataArr)
        that.setData({
          list: list
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);//错误提示信息
    })
    wx.stopPullDownRefresh()

  },
  // 删除
  deleteTap:function(e){
    var that = this;
    var sn = e.currentTarget.dataset.sn;
    var data = {sn:sn}
    wx.showModal({
      title: '提示',
      content: '真的要删除吗？',
      success: function (res) {
        if (res.confirm) {

          wx.showLoading({
            title: '加载中...',
          })
          app.post('agent/deleteDevice', data).then((res) => {
            wx.hideLoading();
            if (res.code == 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
              that.setData({
                list: [],
                pagenum: 1
              })
              that.shopDevice('defalut')
            } else {
              wx.showToast({
                title: "删除失败",
                icon: 'loading',
                duration: 2000
              })
            }
          }).catch((errMsg) => {
            console.log(errMsg);
            wx.hideLoading();
            wx.showToast({
              title: errMsg,
              icon: 'loading',
              duration: 2000
            })
          })
          
        }
      }
    })
  },
  remarkChange:function(e){
    this.setData({
      dialogValue:e.detail
    })
  },
  // 触发备注弹窗
  remarkTap: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    var sn = that.data.list[index].sn;
    var value = type == "room" ? that.data.list[index].remark : that.data.list[index].description;
    that.setData({
      updateType: type,
      thisSN: sn,
      remarkDialog: true,
      dialogValue: value
    })
  },
  // 修改备注，描述
  remarkUpdate() {
    var that = this;
    var list = that.data.list;
    var dialogValue = that.data.dialogValue;
    var thisSN = that.data.thisSN;
    var type = that.data.updateType;
    var url = ''; var data = {}
    if (type == 'room') {
      url = 'agent/updateDeviceRemark';
      data = {
        remark: dialogValue,
        sn: thisSN
      };
    } else {
      url = 'agent/updateDeviceDesc';
      data = {
        desc: dialogValue,
        sn: thisSN
      };
    }
    app.post(url, data).then((res) => {
      if (res.code == 200) {
        wx.showToast({
          title: "success！",
          icon: 'success',
          duration: 2000
        })
        for (var i = 0; i < list.length; i++) {
          if (thisSN == list[i].sn) {
            if (type == 'room') {
              that.setData({
                ['list[' + i + '].remark']: dialogValue
              })
            } else {
              that.setData({
                ['list[' + i + '].description']: dialogValue
              })
            }
          }
        }
      } else {
        wx.showToast({
          title: "Fail！",
          icon: 'loading',
          duration: 2000
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
      wx.showToast({
        title: errMsg,
        icon: 'loading',
        duration: 2000
      })
    })
  },
  // 关闭弹窗
  onClose() {
    this.setData({ remarkDialog: false });
  },
  onPullDownRefresh: function () {
    // 请求最新数据
    this.setData({
      list: [],
      pagenum: 1
    });
    this.shopDevice('defalut');


  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    var pagenum = that.data.pagenum + 1; //获取当前页数并+1
    that.setData({
      pagenum: pagenum, //更新当前页数
    })
    that.shopDevice();//重新调用请求获取下一页数据
  }

})